<?php

namespace app\common\model;

use think\Model;

use app\common\library\Sms as Smslib;

/**
 * 委托交易模型
 */
class Trade Extends Model
{

    // 表名
    // protected $name = 'user_auth';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = '';
    // 追加属性
    protected $append = [
    ];

    // 系统匹配交易
    public function autoMatch($id='')
    {
        $this->clear();

        $info = $this->get($id);

        if(empty($info)){
            return false;
        }
        // 此交易已完成
        if($info['balance'] == 0){
            return true;
        }

        $map = [
            'user_id' => ['neq', $info['user_id']],
            'type' => 1 - $info['type'],
            'balance' => ['gt', 0],
            'status' => 0,
        ];
        $list = $this->where($map)->order('createtime asc')->select();

        // 未匹配到交易信息
        if(empty($list)){
            return false;
        }

        // 总共交易数量
        $total_money = $info['balance'];
        $order = [
            // 'trade_id' => $info['id'],
            'status' => 1,
            'market_price' => $info['market_price'],
        ];
        if ($info['type'] == 0) {

            $order['buyer_trade_id'] = $info['id'];
            $buyer_mobile = db('User')->where('id', $info['user_id'])->value('mobile');

            // 匹配卖出
            foreach ($list as $key => $value) {
                if ($total_money <= 0) {
                    break;
                }
                if ($total_money > $value['balance']) {
                    // 剩余未匹配交易数量
                    $total_money = $total_money - $value['balance'];

                    // 本次匹配的交易数量
                    $trade_money = $value['balance'];
                } else {
                    // 本次匹配的交易数量
                    $trade_money = $total_money;

                    // 剩余未匹配交易数量
                    $total_money = 0;
                }

                // 收款信息
                $authInfo = db('UserAuth')->where('user_id', $value['user_id'])->find();
                $userInfo = db('User')->field('alipay_account, wechat_account, alipay_pic, wechat_pic, mobile')->where('id', $value['user_id'])->find();

                // 生成记录
                $order['buyer_id'] = $info['user_id'];
                $order['seller_id'] = $value['user_id'];
                $order['money'] = $trade_money;
                $order['real_name'] = $authInfo['real_name'];
                $order['bank_name'] = $authInfo['bank_name'];
                $order['branch_bank_name'] = $authInfo['branch_bank_name'];
                $order['bank_card'] = $authInfo['bank_card'];
                $order['seller_trade_id'] = $value['id'];

                // 收款信息
                $order['alipay_account'] = $userInfo['alipay_account'];
                $order['wechat_account'] = $userInfo['wechat_account'];
                $order['alipay_pic'] = $userInfo['alipay_pic'];
                $order['wechat_pic'] = $userInfo['wechat_pic'];

                model('order')->save($order);
                $this->where(['id'=>$value['id']])->setDec('balance', $trade_money);

                // 发送短信
                $seller_mobile = $userInfo['mobile'];
                if ($buyer_mobile) {
                    // Smslib::send($buyer_mobile, NULL, 'trade');
                }
                if ($seller_mobile) {
                    
                }
            }
        } else {

            $order['seller_trade_id'] = $info['id'];
            // 收款信息
            $authInfo = db('UserAuth')->where('user_id', $info['user_id'])->find();
            $userInfo = db('User')->field('alipay_account, wechat_account, alipay_pic, wechat_pic, mobile')->where('id', $info['user_id'])->find();
            $seller_mobile = $userInfo['mobile'];
            
            // 匹配买入
            foreach ($list as $key => $value) {
                if ($total_money <= 0) {
                    break;
                }
                if ($total_money > $value['balance']) {
                    // 剩余未匹配交易数量
                    $total_money = $total_money - $value['balance'];

                    // 本次匹配的交易数量
                    $trade_money = $value['balance'];
                } else {
                    // 本次匹配的交易数量
                    $trade_money = $total_money;

                    // 剩余未匹配交易数量
                    $total_money = 0;
                }

                // 生成记录
                $order['buyer_id'] = $value['user_id'];
                $order['seller_id'] = $info['user_id'];
                $order['money'] = $trade_money;
                $order['real_name'] = $authInfo['real_name'];
                $order['bank_name'] = $authInfo['bank_name'];
                $order['branch_bank_name'] = $authInfo['branch_bank_name'];
                $order['bank_card'] = $authInfo['bank_card'];
                $order['buyer_trade_id'] = $value['id'];

                // 收款信息
                $order['alipay_account'] = $userInfo['alipay_account'];
                $order['wechat_account'] = $userInfo['wechat_account'];
                $order['alipay_pic'] = $userInfo['alipay_pic'];
                $order['wechat_pic'] = $userInfo['wechat_pic'];

                model('order')->save($order);
                $this->where(['id'=>$value['id']])->setDec('balance', $trade_money);

                // 发送短信
                $buyer_mobile = db('User')->where('id', $value['user_id'])->value('mobile');
                if ($buyer_mobile) {
                    
                }
                if ($seller_mobile) {
                    
                }
            }
        }
        // 匹配结束
        $tradeData['balance'] = $info['balance'] - ($info['balance']-$total_money);
        $info->save($tradeData);

    }

    public function clear()
    {
        $time = request()->time() - 3600*24;
        
        // 买方24小时不打款
        $map = [
            'createtime' => ['lt', $time],
            'paytime' => 0,
            'status' => 1,
        ];
        $list = db('order')->where($map)->select();

        if ($list) {
            foreach ($list as $key => $row) {
                db('order')->where('id', $row['id'])->setField('status', 4);

                // 买方委托失效
                db('trade')->where('id', $row['buyer_trade_id'])->data(['status'=>1])->inc('balance', $row['money'])->update();
                db('user')->where('id', $row['buyer_id'])->setField('status', 'hidden');
                // 保留卖方委托
                db('trade')->where('id', $row['seller_trade_id'])->setInc('balance', $row['money']);
            }
        }        

        // 卖方24小不确认放币
        $map = [
            'paytime' => ['lt', $time],
            'finishtime' => 0,
            'status' => 2,
        ];
        $list = db('order')->where($map)->select();
        if ($list) {
            foreach ($list as $key => $row) {
                db('order')->where('id', $row['id'])->setField('status', 3);

                // 放币
                model('trade')->done($row);

                // 卖方委托
                db('trade')->where(['id'=>$row['seller_trade_id'], 'status'=>0])->setField('status', 1);
                db('user')->where('id', $row['seller_id'])->setField('status', 'hidden');
            }
        }
    }

    // 交易成功后的状态设定
    public function checkStatus($id='')
    {
        $map = [
            'id' => $id,
            'status' => 0,
            'balance' => 0,
        ];
        $trade = $this->get($map);
        if ($trade) {
            if ($trade['type'] == 0) {
                $map = [
                    'buyer_trade_id' => $id,
                ];
            }else{
                $map = [
                    'seller_trade_id' => $id,
                ];
            }
            $map['status'] = ['neq', 3];
            $order = db('order')->where($map)->count();
            if ($order<=0) {
                $trade->status = 2;
                $trade->save();
            }
        }
    }

    // 取消交易
    public function cancel($id, $user_id=0)
    {
        $map = [
            'id' => $id,
            'status' => 0,
        ];
        if ($user_id>0) {
            $map['user_id'] = $user_id;
        }
        $trade = $this->get($map);
        if ($trade) {
            if ($trade['type'] == 0) {
                $map = [
                    'buyer_trade_id' => $id,
                ];
            }else{
                $map = [
                    'seller_trade_id' => $id,
                ];
            }
            $map['status'] = ['neq', 3];
            $order = db('order')->where($map)->count();
            if ($order<=0) {
                $trade->status = 1;
                $trade->save();

                if ($trade['type'] == 1) {
                    // 返还余下的财富宝
                    $money = $trade['balance']*(1+$trade['sell_fee_rate']);
                    $user = model('user')->get($trade['user_id']);
                    if ($user && $money>0) {
                        $before = $user->money;
                        $after = $user->money + $money;
                        $frozen_money = $user->frozen_money - $money;
                        $user->save(['money' => $after, 'frozen_money' => $frozen_money]);
                        //写入日志
                        MoneyLog::create(['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => '委托取消，返还余下财富宝', 'date' => date('Ymd'), 'type' => 9]);
                    }
                }

                return true;
            }
        }
        return false;
    }

    // 交易完成的回调函数
    public function done($order)
    {
        $sell_fee_rate = $this->where('id', $order['seller_trade_id'])->value('sell_fee_rate');
        $frozen_money = $order['money']*(1+$sell_fee_rate);
        db('user')->where('id', $order['seller_id'])->setDec('frozen_money', $frozen_money);

        //写入日志
        // model('MoneyLog')->create(['user_id' => $order['seller_id'], 'money' => -$frozen_money, 'before' => $this->auth->money, 'after' => $this->auth->money, 'memo' => '交易完成', 'date' => date('Ymd'), 'type' => 8]);

        // 买家奖励
        $buy_fee = config('site.buy_fee');
        $buy_fee = 0<$buy_fee && $buy_fee<1 ? 1+$buy_fee : 1;
        model('app\common\model\User')->money($order['buyer_id'], $order['money']*$buy_fee, 7, '交易完成', $order['seller_id']);

        $this->checkStatus($order['buyer_trade_id']);
        $this->checkStatus($order['seller_trade_id']);

    }


}
